package cn.itcast.controller.cargo;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.cargo.*;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportProductService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.utils.BeanMapUtils;
import cn.itcast.utils.DownloadUtil;
import cn.itcast.vo.ExportProductVo;
import cn.itcast.vo.ExportResult;
import cn.itcast.vo.ExportVo;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.sun.xml.internal.bind.v2.model.core.ID;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.util.*;

@Controller
@RequestMapping("/cargo/export")
public class ExportController extends BaseController {
//    合同管理/contractList.do  查询已提交的购销合同  select * from co_contract where company_id=? and state=1
    @Reference
    private ContractService contractService;
    @Reference
    private ExportService exportService;
    @Reference
    private ExportProductService exportProductService;

    @RequestMapping(value = "/contractList",name ="查询已提交购销合同数据")
    public String findAll(@RequestParam(defaultValue = "1",name = "page") int pageNum, @RequestParam(defaultValue = "10") int pageSize){
//        查询购销合同的要求是：1、本企业下的数据 2、已提交的数据  3、排序 根据创建时间
        ContractExample example = new ContractExample();
        ContractExample.Criteria criteria = example.createCriteria().andCompanyIdEqualTo(getCompanyId());//添加根据企业id查询的条件
        criteria.andStateEqualTo(1);  //2、已提交的数据
        example.setOrderByClause("create_time desc");  //根据创建时间倒序 排序
        User user = getUser();//获取到当前登录人 从degree判断应该追加什么条件
        Integer degree = user.getDegree();
    /*
        1-企业管理员
        2-管理所有下属部门和人员
        3-管理本部门
        4-普通员工
    */
//        1、企业管理员 超脱于权限之外的
//        2、总经理  在企业管理员基础上 追加了一个条件  create_dept like '当前登录人部门ID%'
//        3、部门经理   在企业管理员基础上 追加了一个条件  create_dept = '当前登录人部门ID'
//        4、普通员工  在企业管理员基础上 追加了一个条件  create_by = '当前登录人ID'
        if(degree==4){
            criteria.andCreateByEqualTo(user.getId());
        }else if(degree==3){
            criteria.andCreateDeptEqualTo(user.getDeptId());
        }else if(degree==2){
            criteria.andCreateDeptLike(user.getDeptId()+"%");
        }
        PageInfo<Contract> pageBean = contractService.findAll(example,pageNum,pageSize);
        request.setAttribute("page",pageBean);
        return "cargo/export/export-contractList";
    }


    @RequestMapping(value = "/list",name ="查询报运单数据")
    public String exportList(@RequestParam(defaultValue = "1",name = "page") int pageNum, @RequestParam(defaultValue = "10") int pageSize){
//        1、查询本企业的   2、排序 create_time desc
        ExportExample exportExample = new ExportExample();
        exportExample.createCriteria().andCompanyIdEqualTo(getCompanyId());
        exportExample.setOrderByClause("create_time desc");

        PageInfo pageInfo = exportService.findAll(exportExample, pageNum, pageSize);
        request.setAttribute("page",pageInfo);

        return "cargo/export/export-list";
    }

    @RequestMapping(value = "/toExport",name ="填写报运单页面")
    public String toExport(String id){
        request.setAttribute("id",id);

        return "cargo/export/export-toExport";
    }
    @RequestMapping(value = "/edit",name ="报错报运单方法")
    public String edit(Export export){
        User user = getUser();
//        需要保存3张表数据 涉及到6张表
        if(StringUtils.isEmpty(export.getId())){  //id为空 就是新增
//            新增时有默认值：1、ID 2、企业ID  3、 企业名称  4、创建时间   5、创建人id  6、创建人的部门id 7、状态 0草稿状态
            export.setId(UUID.randomUUID().toString());
            export.setCreateTime(new Date());
            export.setCompanyId(user.getCompanyId());
            export.setCompanyName(user.getCompanyName());
            export.setCreateBy(user.getId());
            export.setCreateDept(user.getDeptId());
            export.setState(0);
            exportService.save(export);
        }else{
            export.setUpdateTime(new Date());
            export.setUpdateBy(user.getId());
            exportService.update(export);
        }
        return "redirect:/cargo/export/list.do";
    }


    @RequestMapping(value = "/toUpdate",name ="进入到报运单编辑页面")
    public String toUpdate(String id){  // 报运单的id
//        页面中需要的数据有 1、报运单对象 2、当前报运单下货物的集合
        Export export = exportService.findById(id);
//        select * from co_export_product where  export_id=??
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);

        request.setAttribute("export",export);
        request.setAttribute("eps",exportProductList);


        return "cargo/export/export-update";
    }


    @RequestMapping(value = "/exportE",name ="海关电子报运")
    public String exportE(String id){  //报运单的id

//        第一阶段：准备数据ExportVo
//        报运时需要的数据有：1、报运单对象 2、这个报运单下货物对象
//           Export---->ExportVo
//           ExportProduct--->ExportProductVo

        Export export = exportService.findById(id);

        ExportVo exportVo = new ExportVo();
        BeanUtils.copyProperties(export,exportVo);
        exportVo.setExportId(id);
//        select * from co_export_product where  export_id=??
        List<ExportProduct> exportProductList = exportProductService.findByExportId(id);
        for (ExportProduct exportProduct : exportProductList) {
            ExportProductVo exportProductVo = new ExportProductVo();
            BeanUtils.copyProperties(exportProduct,exportProductVo);
//            需要手动个Vo设置的是：eid 、exportProductId
            exportProductVo.setEid(exportVo.getId());
            exportProductVo.setExportProductId(exportProduct.getId());
            exportVo.getProducts().add(exportProductVo);
        }

//        第二阶段：远程调用
        WebClient.create("http://localhost:9090/ws/export/ep").post(exportVo);

//        第三阶段：根据报运单id远程获取结果
        ExportResult exportResult = WebClient.create("http://localhost:9090/ws/export/ep/" + id).get(ExportResult.class);
//        第四阶段：把返回的结果保存到表中
        exportService.exportE(exportResult);

        return "redirect:/cargo/export/list.do";
    }

    @Autowired
    private DownloadUtil downloadUtil;

    @RequestMapping(value = "/exportPdf",name ="导出报运单pdf")
    @ResponseBody
    public void exportPDF(String id) throws Exception{
        Export export = exportService.findById(id); //查询报运单

        List<ExportProduct> exportProductList = exportProductService.findByExportId(id); //查询报运单下货物

//        1、读取模板
        String realPath = session.getServletContext().getRealPath("/make/pdf/export.jasper");
        FileInputStream inputStream = new FileInputStream(realPath);
//        使用一个工具类 直接可以把一个bean转成一个map
        Map parameters =BeanMapUtils.beanToMap(export);

        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(exportProductList);

        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, dataSource);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint,byteArrayOutputStream);
        downloadUtil.download(byteArrayOutputStream,response,"报运单.pdf");
    }
}
